package com.yanchi.shiro.realm;

import com.yanchi.service.UserService;
import com.yanchi.entity.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

// 自定义realm
public class CustomerRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    // 认证方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 前端传的username
        String principal = (String) token.getPrincipal();

        // 数据库查询是否有当前用户
        User user = userService.queryByUsername(principal);

        if (user != null){
            // 取出数据库的密码
            String password = user.getPassword();
            // 取出数据库的slot
            String slot = user.getSlot();
            return new SimpleAuthenticationInfo(
                    principal,
                    password,
                    ByteSource.Util.bytes(slot),
                    this.getName()
            );
        }

//        if ("yanchi".equals(principal)){
//            return new SimpleAuthenticationInfo(principal,"123456",this.getName());
//        }
        return null;
    }
}
